package yunjiao.javatutorials.lang.concurrent.interrupt;

/**
 * 使用 InterruptedException 处理阻塞操作
 *
 * @author yangyunjiao
 */
public class BlockingOperationExample {
    public static void main(String[] args) throws InterruptedException {
        Thread blockingThread = new Thread(new BlockingTask());
        blockingThread.start();

        Thread.sleep(2000);
        blockingThread.interrupt();
    }

    static class BlockingTask implements Runnable {
        @Override
        public void run() {
            try {
                // 模拟可能阻塞的操作
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println("执行阻塞操作前检查中断");

                    // 模拟阻塞操作（如I/O、网络请求等）
                    Thread.sleep(1000);

                    System.out.println("阻塞操作完成");
                }
            } catch (InterruptedException e) {
                System.out.println("线程在阻塞操作中被中断");
                System.out.println("清理资源...");
                // 恢复中断状态，让调用者知道发生了中断
                Thread.currentThread().interrupt();
            }
            System.out.println("阻塞任务线程结束");
        }
    }
}
